package previous.Test_0218;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
public class Solution {
    //链表
    //两数相加
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int t=0;
        ListNode newhead=new ListNode(0);
        ListNode cur=newhead;
        //当最后都遍历完，两相加大于10，t还不为0，还要继续相加
        while(l1!=null || l2!=null  || t!=0){
            if(l1!=null){
                t+=l1.val;
                l1=l1.next;
            }
            if(l2!=null){
                t+=l2.val;
                l2=l2.next;
            }
            cur.next=new ListNode(t%10);
            t/=10;
            cur=cur.next;
        }
        return newhead.next;
    }
    //两两交换链表中的节点
    public ListNode swapPairs(ListNode head) {
        //如果节点为空或者只有一个节点
        if(head==null || head.next==null){
            return head;
        }
        ListNode newHead=new ListNode(0);
        newHead.next=head;
        ListNode prev=newHead;
        ListNode cur=head;
        ListNode next=cur.next;
        ListNode nnext=next.next;
        while(cur!=null && next!=null){
            //交换
            prev.next=next;
            next.next=cur;
            cur.next=nnext;
            //修改
            prev=cur;
            cur=nnext;
            if(cur!=null)next=cur.next;
            if(next!=null)nnext=next.next;
        }
        return newHead.next;
    }

}
